// 1. 导入创建切片的方法
import { createSlice } from '@reduxjs/toolkit'

// 2. 创建一个切片
const appSlice = createSlice({
    name: 'user',// 定义切片名称
    initialState: {
        loginState: localStorage.getItem('loginState') == 'true',
        adminname: localStorage.getItem('adminname') || '',
        checkedkeys: JSON.parse(localStorage.getItem('checkedkeys')) || [],
        role: localStorage.getItem('role') * 1 || 1,
        token: localStorage.getItem('token') || ''
    },
    reducers: {
        changeUser(state, action) {
            state.adminname = action.payload.adminname
            state.loginState = action.payload.loginState
            state.checkedkeys = action.payload.checkedkeys
            state.role = action.payload.role
            state.token = action.payload.token

            // 将用户登录信息保存在本地防止刷新页面时数据丢失
            localStorage.setItem('adminname', action.payload.adminname)
            localStorage.setItem('loginState', action.payload.loginState)
            localStorage.setItem('checkedkeys', JSON.stringify(action.payload.checkedkeys))
            localStorage.setItem('role', action.payload.role)
            localStorage.setItem('token', action.payload.token)
        }
    }
})

export const { changeUser } = appSlice.actions

export default appSlice.reducer